package ext;

import com.jfinal.plugin.activerecord.generator.ColumnMeta;
import com.jfinal.plugin.activerecord.generator.MetaBuilder;
import com.jfinal.plugin.activerecord.generator.TableMeta;

import javax.sql.DataSource;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by ming on 2018/8/27.
 * desc：
 */
public class SqliteMetaBuilder extends MetaBuilder {
    Map<String,String> sqlliteTypeMapping;


    public SqliteMetaBuilder(DataSource dataSource) {
        super(dataSource);
        sqlliteTypeMapping = new HashMap<String,String>();
        sqlliteTypeMapping.put("VARCHAR",String.class.getName());
        sqlliteTypeMapping.put("NUMERIC",Integer.class.getName());
        sqlliteTypeMapping.put("BIGINT",Long.class.getName());
        sqlliteTypeMapping.put("INTEGER",Integer.class.getName());
        sqlliteTypeMapping.put("REAL",Double.class.getName());
        sqlliteTypeMapping.put("BLOB","[B");

        //TODO: 补全类型列表
        sqlliteTypeMapping.put("TEXT",String.class.getName());
    }


    @Override
    protected void buildColumnMetas(TableMeta tableMeta) throws SQLException {
        PreparedStatement stm = this.conn.prepareStatement("SELECT sql FROM sqlite_master WHERE type = 'table' AND tbl_name = ?");
        stm.setString(1,tableMeta.name);
        ResultSet rs = stm.executeQuery();
        while(rs.next()){
            String dml = rs.getString(1);
            int start = dml.indexOf('(')+1;
            int end = dml.lastIndexOf(')');
            String colsStr = dml.substring(start,end);
            String[] colArray = colsStr.split(",");
            for(String colMetaStr:colArray){
                String[] colMetaParts = colMetaStr.trim().split("[\\s\\(\\)]");
                System.out.println(Arrays.toString(colMetaParts));
                ColumnMeta cm = new ColumnMeta();
                cm.name = colMetaParts[0].replace("\"","");
                cm.javaType = sqlliteTypeMapping.get(colMetaParts[1].toUpperCase());
                if(cm.javaType==null){
                    cm.javaType = "java.lang.String";
                }
                cm.attrName = this.buildAttrName(cm.name);
                tableMeta.columnMetas.add(cm);
            }
        }

        rs.close();
        stm.close();
    }
}